/*
 * Copyright (c) 2024 iSOFT INFRASTRUCTURE SOFTWARE CO., LTD.
 * easyAda is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */

#ifndef MUTEX_H
#define MUTEX_H

#include <core/object.h>
#include <core/task.h>

#include <stdlib/stdint.h>
#include <tools/list.h>

typedef struct mutex {
    atomic_t lock;
    list_t   wait_list;
    tcb_t   *owner;
    list_t   ownerlist;
    int      maxsem;
    object_t obj;
} DEFAULT_ALINMENT mutex_t;

static inline void mutex_get(mutex_t *mutex)
{
    object_get(&mutex->obj);
}

static inline void mutex_put(mutex_t *mutex)
{
    object_put(&mutex->obj, offset_of(mutex_t, obj), sizeof(mutex_t));
}

void          mutex_init(mutex_t *mutex, int sema);
void          mutex_lock(mutex_t *mutex);
void          mutex_unlock(mutex_t *mutex);
int           mutex_trylock(mutex_t *mutex);
cptr_t        mutex_owner(mutex_t *mutex);
unsigned long mutex_destroy(capability_t *cap, mutex_t *mutex);

#endif
